<?php
namespace App\Console\Commands;

use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;

/**
 * Class ModelCommand
 * @package App\Console\Commands
 */
class AdminControllerCommand extends Command {
    /**
     * @var string
     */
    protected $signature = 'create:admin_controller {--table=} {--path=}';
    /**
     * @var string
     */
    protected $basePath = 'app/Http/Controllers/Admin';
    use CommandTrait;

    /**
     * @name: handle
     * @author: lisa
     * @datetime: 2021/8/3 10:37
     */
    public function handle() {
        $table = $this->option('table');
        $basePath = $this->option('path');
        $this->basePath = $basePath ?: $this->basePath;
        if (!$table) $this->error('请输入表名');
        if (!$this->isTableExists($table)) $this->error("该表不存在");
        $plural = Str::singular($table);
        $modelName = Str::studly($plural);
        $fileName  = "{$plural}Controller.php";
        $fileName  = $this->getFileName($fileName);
        $path      = $this->getPath($fileName);
        $structure = $this->getTableStructure($table);
        list($namespace, $className) = $this->getNamespaceAndClassName($path);
        list($columns, $primaryKey) = $this->getTableColumnsAndPrimaryKeyAndWhereSymbols($structure);
        $this->render($path, [
            'table'         => $table,
            'pageDir'       => $plural,
            'modelName'     => $modelName,
            'namespace'     => $namespace,
            'className'     => $className,
            'columnMap'     => $this->getColumnMap($columns),
            'primaryKey'    => $primaryKey,
        ], $this->getRenderHtml());
    }

    /**
     * 获取表列、主键、查询条件
     * @name: getTableColumnsAndPrimaryKeyAndWhereSymbols
     * @param $tableStructure
     * @return array
     * @author: lisa
     * @datetime: 2021/8/3 11:09
     */
    public function getTableColumnsAndPrimaryKeyAndWhereSymbols($tableStructure): array
    {
        $primaryKey = null;
        $columns = [];
        foreach ($tableStructure as $k => $v) {
            $field = Arr::get($v, 'Field');
            $type = Arr::get($v, 'Type');
            $key = Arr::get($v, 'Key');
            if ($this->isPrimaryKey($key)) $primaryKey = $field;
            $columns[] = $field;
        }
        return [$columns, $primaryKey];
    }

    /**
     * @param $columns
     * @return string
     * @name:getColumnMap
     * @author: lisa
     * @datetime: 2021/11/16 19:43
     */
    public function getColumnMap($columns) {
        $str = "";
        foreach ($columns as $k => $v) {
            $str.= "\t\t\t".'$data->'.$v.' = '.'$request->get("'.$v.'");'."\n";
        }
        return $str;
    }

    /**
     * @name: getRenderHtml
     * @return string
     * @author: lisa
     * @datetime: 2021/8/3 11:53
     */
    public function getRenderHtml() {
        return <<<html
<?php
namespace {namespace};
use App\Models\{modelName};
use Illuminate\Http\Request;
use App\Exceptions\ExceptionSms;
use Carbon\Carbon;
use App\Helpers\MoneyHelper;

class {className} extends CommonController
{
    public function dataList() {
        \$list = {modelName}::bgBaseQuery(\$this->input())->paginate(\$this->limit);
        return ExceptionSms::returnSuccess(\$list->items(), \$list->total());
    }
    public function getInfo() {
        ExceptionSms::checkParams(\$this->input(), [
            'id' => 'required|integer|min:1',
        ]);
        \$id = \$this->input('id') ?? 0;
    }
    public function dataSave(Request \$request) {
        \$id = \$request->get('id') ?? "";
        if (\$id) \$data = {modelName}::getOneById(\$id);
        else \$data = new {modelName}();
        {columnMap}
        \$data->save();
        return ExceptionSms::returnSuccess();
    }
    public function deletes() {
        ExceptionSms::checkParams(\$this->input(), [
            'ids' => 'required|array'
        ]);
        \$ids = \$this->input('ids') ?? [];
        if (!is_array(\$ids)) ExceptionSms::returnError('请求参数错误');
        if (!collect(\$ids)->count()) ExceptionSms::returnError('请勾选数据');
        {modelName}::whereIds(\$ids)->update([
            'is_delete' => 1,
            'updated_at' => Carbon::now()->toDateTimeString()
        ]);
        return ExceptionSms::returnSuccess();
    }
    public function enables() {
        ExceptionSms::checkParams(\$this->input(), [
            'ids' => 'required|array'
        ]);
        \$ids = \$this->input('ids') ?? [];
        if (!is_array(\$ids)) ExceptionSms::returnError('请求参数错误');
        if (!collect(\$ids)->count()) ExceptionSms::returnError('请勾选数据');
        {modelName}::whereIds(\$ids)->update([
            'is_enable' => 1,
            'updated_at' => Carbon::now()->toDateTimeString()
        ]);
        return ExceptionSms::returnSuccess();
    }
    public function disables() {
        ExceptionSms::checkParams(\$this->input(), [
            'ids' => 'required|array'
        ]);
        \$ids = \$this->input('ids') ?? [];
        if (!is_array(\$ids)) ExceptionSms::returnError('请求参数错误');
        if (!collect(\$ids)->count()) ExceptionSms::returnError('请勾选数据');
        {modelName}::whereIds(\$ids)->update([
            'is_enable' => 0,
            'updated_at' => Carbon::now()->toDateTimeString()
        ]);
        return ExceptionSms::returnSuccess();
    }
}
html;
    }

}
